package com.example.demo.utils.IpUtils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;

import static com.example.demo.mapper.Ip.Constant.IP_URL;

/**
 * @author coderJim
 * @date 2023-10-16 14:07
 */
public class AddressUtils {

    // 未知地址
    public static final String UNKNOWN = "XX XX";
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
    // 假设LOCAL_IP为本地IP的表示，根据实际情况定义
    private static final String LOCAL_IP = "0:0:0:0:0:0:0:1"; // 或 "127.0.0.1" 对 IPv4

    // 定义内网IP的返回格式
    private static final String INTERNAL_IP_ADDRESS = "内网IP";

    public static String getRealAddressByIP(String ip) {
        // 对于内网IP，直接返回预定义的地址
        if (ip.equals(LOCAL_IP) || "127.0.0.1".equals(ip)) {
            // 如果需要，这里可以记录日志
            log.info("内网IP查询: {}", ip);
            return INTERNAL_IP_ADDRESS;
        }
        try {
            String rspStr = sendGet(IP_URL, "ip=" + ip + "&json=true", "GBK");
            if (StringUtils.isBlank(rspStr)) {
                log.error("获取地理位置异常，返回结果为空 {}", ip);
                return UNKNOWN;
            }
            JSONObject obj = JSONObject.parseObject(rspStr);
            String region = obj.getString("pro");
            String city = obj.getString("city");
            return String.format("%s %s", region, city);
        } catch (Exception e) {
            log.error("获取地理位置异常 {}, 异常信息: {}", ip, e.getMessage(), e);
        }
        return UNKNOWN;
    }

    public static String sendGet(String url, String param, String contentType) {
        // 检查是否是本地回环地址的查询
        if (param.contains("127.0.0.1") || param.contains("0:0:0:0:0:0:0:1")) {
            log.info("本地回环IP查询: {}", param);
            return "本地回环地址 - 无法查询地理位置";
        }
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }
}

